package com.wang.application.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.application.api.menu.deleteMenu.DeleteMenuRequest;
import com.wang.application.api.menu.queryAllMenu.QueryAllMenuRequest;
import com.wang.application.api.menu.saveMenu.SaveMenuRequest;
import com.wang.application.mapper.DaMenuMapper;
import com.wang.application.model.DaMenu;
import com.wang.application.service.DaMenuService;
import com.wang.common.common.AService;
import com.wang.common.common.ErrorCode;
import com.wang.common.exception.BusinessException;
import com.wang.common.utils.Contact;
import com.wang.common.utils.MybatisUtil;
import com.wang.common.utils.Utils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author Mr.wang
 * @description 针对表【da_menu(菜单表)】的数据库操作Service实现
 * @createDate 2022-11-02 10:01:09
 * RequiredArgsConstructor:注入需要写很多@Autowried注解，此注解是lombok提供的一个注解，可以代替@Autowried注解，需要注意的是在注入时需要用final定义，或者使用@NotNull注解
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class DaMenuServiceImpl extends ServiceImpl<DaMenuMapper, DaMenu>
        implements DaMenuService {

//    @Resource
    private final DaMenuMapper daMenuMapper;

    @Resource(name = "aService")
    private AService aService;

    @Override
    public Page<DaMenu> queryAllMenu(QueryAllMenuRequest request) {
        log.info("\n=======================QueryAllMenuRequest:{}", request);

        // 1、查询用户权限
        aService.authValid();
        // 2、分页查询
        QueryWrapper<DaMenu> queryWrapper = new QueryWrapper<>();
        MybatisUtil.queryFilter(queryWrapper, request.equalTransfer());
        MybatisUtil.queryLikeFilter(queryWrapper, request.likeTransfer());
        if (Utils.isNotEmpty(request.getStarttime())) queryWrapper.ge("createtime", request.getStarttime());
        if (Utils.isNotEmpty(request.getEndtime())) queryWrapper.le("createtime", request.getEndtime());
        if ("0".equals(request.getSort())) {
            queryWrapper.orderByDesc("menuid");
        } else {
            queryWrapper.orderByAsc("menuid");
        }
        Page<DaMenu> page = new Page<>(request.getCurrent(), request.getSize());
        daMenuMapper.selectPage(page, queryWrapper);
        return page;
    }

    @Override
    public Boolean saveMenu(SaveMenuRequest request) {
        log.info("\n=======================SaveMenuRequest:{}", request);

        // 1、用户权限校验
        aService.authValid();
        // 2、数据校验
        if (Utils.isAnyBlank(request.getMenuid(), request.getMenucode(), request.getFatherid(), request.getMenuname(), request.getOperation()))
            throw new BusinessException(ErrorCode.NULL_ERROR, "请求参数为空");
        if (request.getMenucode().length() != 3)
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "菜单码长度错误");
        // 菜单码重复查询
        QueryWrapper<DaMenu> menuQueryWrapper = new QueryWrapper<>();
        menuQueryWrapper.eq("menucode", request.getMenucode());
        menuQueryWrapper.ne("menuid", request.getMenuid());
        Long count = daMenuMapper.selectCount(menuQueryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "菜单码重复");
        }
        // 父级菜单存在查询
        menuQueryWrapper = new QueryWrapper<>();
        menuQueryWrapper.eq("menuid", request.getFatherid());
        count = daMenuMapper.selectCount(menuQueryWrapper);
        if (count < 1) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "父级菜单不存在");
        }
        // 3、保存数据
        boolean result;
        DaMenu transfer = request.transfer();
        // 菜单存在查询
        menuQueryWrapper = new QueryWrapper<>();
        menuQueryWrapper.eq("menuid", request.getMenuid());
        count = daMenuMapper.selectCount(menuQueryWrapper);
        if ("1".equals(request.getOperation())) {
            // 修改菜单
            if (count < 1) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "菜单不存在");
            }
            UpdateWrapper<DaMenu> updateWrapper = MybatisUtil.updateFilter(transfer);
            updateWrapper.eq("menuid", transfer.getMenuid());
            try {
                result = update(updateWrapper);
            } catch (Exception e) {
                log.error("数据库更新菜单失败", e);
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "数据库更新菜单失败");
            }
            return result;
        }
        // 新增菜单
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "菜单已存在");
        }
        transfer.setCreatetime(Utils.convertDateToString());//创建时间
        transfer.setStatus(Contact.Status.ACTIVE);//激活状态 1：激活
        int insert;
        try {
            insert = daMenuMapper.insert(transfer);
        } catch (Exception e) {
            log.error("数据库新增菜单失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "数据库新增菜单失败");
        }
        return insert == 1;
    }

    @Override
    public Boolean deleteMenu(DeleteMenuRequest request) {
        log.info("\n=======================DeleteMenuRequest:{}", request);

        // 1、用户权限校验
        aService.authValid();
        // 2、数据校验
        if (Utils.isEmpty(request.getMenuid())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "菜单ID为空");
        }
        // 菜单查询
        QueryWrapper<DaMenu> menuQueryWrapper = new QueryWrapper<>();
        menuQueryWrapper.eq("menuid", request.getMenuid());
        DaMenu daMenu = daMenuMapper.selectOne(menuQueryWrapper);
        if (daMenu == null || !request.getMenuid().equals(daMenu.getMenuid())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "菜单不存在");
        }
        // 3、删除菜单
        int result;
        try {
            result = daMenuMapper.delete(menuQueryWrapper);
        } catch (Exception e) {
            log.error("数据库删除菜单失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "数据库删除菜单失败");
        }
        return result == 1;
    }
}




